<!-- TODO: YOUR CODE HERE -->
<template>
    <el-scrollbar height="100%" style="width: 100%; height: 100%; ">
      <div style="margin-top: 20px; margin-left: 40px; font-size: 2em; font-weight: bold;">
            商品检索
      </div>
      <!--   搜索框   -->
      <div style="margin: 30px 10% 5px 10%; width: 80%; display: inline-flex">
        <el-input
            prefix-icon="search"
            placeholder="请输入商品名称"
            v-model="searchInfo"
            style="margin-right: 5%; width:80%"></el-input>
        <el-button
            type="primary"
            style="width: 20%"
            @click="SearchProduct">
            搜索
        </el-button>
      </div>
      <!--   搜索历史记录   -->
      <div style="margin-left: 10%; margin-bottom: 5px; width: 80%; font-size: small; color: #999999; display: inline-flex">
        <a>搜索历史：</a>
        <a v-for="(item, index) in historySearch" :key="index" @click="searchInfo=item; this.SearchProduct()"> {{item}} </a>
      </div>
      <!--   搜索选项   -->
      <div style="width: 80%; margin-left: 10%; margin-right: 10%">
        <div>
          <el-button @click="loginPlatformNum=0; this.CheckCookies(0)"
                     type="primary" size="small" plain>
            京东登录
            <span v-if="searchSettings.searchPlatform.is_jd_search">(已登录)</span>
            <span v-if="! searchSettings.searchPlatform.is_jd_search">(未登录)</span>
          </el-button>
          <el-button @click="loginPlatformNum=2; this.CheckCookies(2)"
                     type="primary" size="small" plain>
            苏宁登录
            <span v-if="searchSettings.searchPlatform.is_sn_search">(已登录)</span>
            <span v-if="! searchSettings.searchPlatform.is_sn_search">(未登录)</span>
          </el-button>
        </div>

        <div>
          <el-radio label="ascending" v-model="searchSettings.sort_type">升序排列</el-radio>
          <el-radio label="descending" v-model="searchSettings.sort_type">降序排列</el-radio>
        </div>

      </div>
      <!--    搜索结果    -->
        <div style="display: flex;flex-wrap: wrap; justify-content: start;">
          <div class="productCard"
           v-for="product in searchResults"
           v-show="product.name"
           :key="product.product_url">
            <el-card class="cardBox">
              <img :src="product.pic_url" style="width: 100%; display: block"
                   @click="JumpToProduct(product.product_url)" alt="描述图"/>
              <div style="padding: 10px;">
                <div class="priceShow">
                  <span> {{product.price}} </span>
                </div>
                <div class="titleShow">
                  <span style="font-size: 10px" :title="product.name">{{product.name}}</span>
                </div>
                <div style="display: flex">
                  <el-button
                      @click="GetChartData(product.product_id, product.group_num)"
                      style="width: 50%"
                      type="primary" size="small" plain>价格曲线</el-button>
                  <el-button
                      @click="addTraceInfo.platform=product.group_num;
                      addTraceInfo.product_name=product.name;
                      addTraceInfo.product_id=product.product_id;
                      addTraceVisible=true; "
                      style="width: 40%"
                      type="primary" size="small" plain>追踪</el-button>
                </div>
                <div class="merchantShow">
                  <span style="font-size: 12px; color: #999" :title="product.merchant">{{product.merchant}}</span>
                </div>
              </div>
            </el-card>
          </div>
        </div>
      <!--   正在搜索的提示   -->
        <div class="loading" v-show="isSearching">
          <div class="load-box">
            <img src="../components/icons/loading.gif" alt="搜索中...">
            <span>搜索中...</span>
          </div>
        </div>
      <!-- 商品历史价格对话框 -->
      <el-dialog
          v-model="historyPriceVisible"
          @open="OpenChart"
          @close="CloseChart"
          title="商品历史价格折线图"
          width="30%" align-center>
        <div
            style="width: 100%; height: 200px"
            ref="historyPriceChart">图表加载中...</div>
      </el-dialog>
      <!-- 新建追踪商品对话框 -->
        <el-dialog v-model="addTraceVisible" title="新建追踪商品" width="30%" align-center>
            <div style="margin-left: 2vw; font-weight: bold; font-size: 1rem; margin-top: 20px; ">
                平台：
              <span v-if="addTraceInfo.platform === 0" style="width: 12.5vw;"> 京东 </span>
              <span v-if="addTraceInfo.platform === 1" style="width: 12.5vw;"> 淘宝 </span>
              <span v-if="addTraceInfo.platform === 2" style="width: 12.5vw;"> 苏宁 </span>
            </div>
            <div style="margin-left: 2vw; font-weight: bold; font-size: 1rem; margin-top: 20px; ">
                商品ID：
              <span style="width: 12.5vw;">{{addTraceInfo.product_id}}</span>
            </div>
            <div style="margin-left: 2vw; font-weight: bold; font-size: 1rem; margin-top: 20px; ">
                商品名称：
              <span style="width: 12.5vw;"> {{addTraceInfo.product_name}} </span>
            </div>
            <div style="margin-left: 2vw; font-weight: bold; font-size: 1rem; margin-top: 20px; ">
                预期价格：
                <el-input v-model.number="addTraceInfo.target_price" type="number" style="width: 12.5vw;" clearable />
            </div>

            <template #footer>
                <span>
                    <el-button @click="addTraceVisible=false">取消</el-button>
                    <el-button type="primary" @click="ConfirmNewTrace"
                        :disabled="addTraceInfo.target_price <= 0">确定</el-button>
                </span>
            </template>
        </el-dialog>
      <!-- 扫码界面 -->
        <el-dialog
            @close="HandleClose"
            v-model="qrCodeVisible"
            title="扫码登录"
            style="text-align: center"
            width="30%" align-center>
          <img :src="qrImgUrl" style="width: 100%; display: block" alt="登录二维码加载中..."/>
          <el-button
              style="margin-top: 10px"
              @click="this.GetQrCode(loginPlatformNum)"
              type="primary" plain>重新获取二维码</el-button>
        </el-dialog>
    </el-scrollbar>
</template>

<script>
import axios from 'axios';
import { ElMessage } from 'element-plus'
import {ref} from "vue";
import {Discount, Star} from "@element-plus/icons-vue";
import * as echarts from "echarts"

export default {
  components: {Star, Discount},
  data() {
    return {
      isSearching: false,
      historySearch: [],
      searchInfo: "",
      qrImgUrl: "",
      loginPlatformNum: 0,
      intervalId: 0,
      searchSettings: {
        searchPlatform: {
          is_jd_search: ref(false),
          is_tb_search: ref(false),
          is_sn_search: ref(true),
        },
        sort_type: "",
      },
      searchResults: [
        {
          name: "",
          price: 0.0,
          group_num: 0,
          product_id: "",
          product_url: "",
          pic_url: "",
          merchant: "",
        }
      ],
      historyProduct: {
        historyTime: [],
        historyPrice: [],
      },
      addTraceInfo: {
        platform: 0,
        product_name: "",
        product_id: "",
        target_price: 0,
      },
      historyPriceVisible: false,
      addTraceVisible: false,
      qrCodeVisible: false,
      chart: null,
    }
  },
  computed: {

  },
  methods: {
    CheckLogin(platform_num) {
      axios.post("/product/check/cookie/",
          {
            group_num: platform_num
          })
          .then(response => {
            if (response.data.is_cookie_store) {
              if (platform_num === 0) {
                this.searchSettings.searchPlatform.is_jd_search = true
              }
              else if (platform_num === 1) {
                this.searchSettings.searchPlatform.is_tb_search = true
              }
              else if (platform_num === 2) {
                this.searchSettings.searchPlatform.is_sn_search = true
              }
            }
          })
          .catch(error => {
            console.log("检查登录状况失败", error)
          })
    },
    CheckCookies(platform_num) {
      this.qrImgUrl = ""
      axios.post("/product/check/cookie/",
          {
            group_num: platform_num
          })
          .then(response => {
            if (!response.data.is_cookie_store) {
              this.qrCodeVisible = true
              this.GetQrCode(platform_num)
              this.CheckLoginStatus(platform_num)
            } else {
              let platform = ""
              if (platform_num === 0) {
                platform = "京东"
              } else if (platform_num === 1) {
                platform = "淘宝"
              } else if (platform_num === 2) {
                platform = "苏宁"
              }
              ElMessage.success("您已登录"+platform)
            }
          })
          .catch(error => {
            console.log("获取cookie失败", error)
          })
          .finally(() => {
            this.EndCheck()
          })
    },
    GetQrCode(platform_num) {
      axios.post("/product/check/qrcode/",
          {
            user_id: sessionStorage.getItem('user_id'),
            group_num: platform_num
          })
          .then(response => {
            this.qrImgUrl = "http://localhost:8000/product/image/qrcode/" + response.data.qr_img_name + `?timestamp=${new Date().getTime()}`
            console.log(this.qrImgUrl)
          })
          .catch(error => {
            console.log(error)
          })
    },
    CheckLoginStatus(platform_num) {
      this.intervalId = setInterval(() => {
          axios.post('/product/check/loginstatus/',
            {
              user_id: sessionStorage.getItem('user_id'),
              group_num: platform_num
            })
            .then(response => {
              console.log(response)
              if (response.data.is_login) {
                ElMessage.success("登录成功")
                this.qrCodeVisible = false
                if (platform_num === 0) {
                  this.searchSettings.searchPlatform.is_jd_search = true
                }
                else if (platform_num === 1) {
                  this.searchSettings.searchPlatform.is_tb_search = true
                }
                else if (platform_num === 2) {
                  this.searchSettings.searchPlatform.is_sn_search = true
                }
                clearInterval(this.intervalId)
                location.reload()
              }
            })
            .catch(error => {
              console.error("轮询报错", error)
              ElMessage.error("登录失败！请重新登录")
              clearInterval(this.intervalId)
            })
      }, 4000)
    },
    EndCheck() {
      axios.post('/product/check/close/',
          {
            user_id: sessionStorage.getItem('user_id'),
          })
          .then(response => {
            console.log("结束检查")
          })
          .catch(error => {
            console.log("结束检查报错", error)
          })
    },
    HandleClose() {
      clearInterval(this.intervalId)
      this.EndCheck()
      ElMessage.error("登录失败，请重新登录")
      location.reload()
    },
    SearchProduct() {
      this.isSearching = true
      this.searchResults = []
      if (this.searchInfo !== "") {
        let val = this.searchInfo.trim()
        if (!val) return
        let index = this.historySearch.indexOf(val)
        if (index === -1) {
          this.historySearch.unshift(val)
          this.historySearch = this.historySearch.slice(0, 10)
          localStorage.setItem('historySearch', JSON.stringify(this.historySearch))
        } else {
          this.historySearch.splice(index, 1)
          this.historySearch.unshift(val)
          localStorage.setItem('historySearch', JSON.stringify(this.historySearch))
        }
      }
      axios.post("/product/search/",
          {
            is_jd_search: this.searchSettings.searchPlatform.is_jd_search,
            is_tb_search: this.searchSettings.searchPlatform.is_tb_search,
            is_sn_search: this.searchSettings.searchPlatform.is_sn_search,
            sort_type: this.searchSettings.sort_type,
            search_info: this.searchInfo
          })
          .then(response => {
            ElMessage.success("搜索成功")
            console.log(response)
            if (this.searchSettings.searchPlatform.is_jd_search === true
             && response.data.is_jd_search === false)
            {
              this.searchSettings.searchPlatform.is_jd_search = response.data.is_jd_search
              ElMessage.warning("京东登录凭证已失效，请重新登录！")
            }
            if (this.searchSettings.searchPlatform.is_tb_search === true
             && response.data.is_tb_search === false)
            {
              this.searchSettings.searchPlatform.is_tb_search = response.data.is_tb_search
              ElMessage.warning("淘宝登录凭证已失效，请重新登录！")
            }
            if (this.searchSettings.searchPlatform.is_sn_search === true
             && response.data.is_sn_search === false)
            {
              this.searchSettings.searchPlatform.is_sn_search = response.data.is_sn_search
              ElMessage.warning("苏宁登录凭证已失效，请重新登录！")
            }
            let products = response.data.search_result
            products.forEach(product => {
              this.searchResults.push(product)
            })
          })
          .catch(error => {
            ElMessage.error("搜索失败")
            console.log(error)
          })
          .finally(() => {
            this.isSearching = false
          })
    },
    JumpToProduct(product_url) {
      window.open(product_url)
    },
    GetChartData(product_id, group_num) {
      axios.post("/product/history/",
          {
            platform: group_num,
            product_id: product_id,
          })
          .then(response => {
            this.historyProduct.historyPrice = response.data.price_list
            this.historyProduct.historyTime = response.data.date_list
            this.historyPriceVisible=true
          })
          .catch(error => {
            console.log("获取折线图数据失败", error)
          })
    },
    DrawHistoryChart() {
      this.chart = echarts.init(this.$refs.historyPriceChart)
      // 绘制图表
      this.chart.setOption({
        xAxis: {
          data: this.historyProduct.historyTime
        },
        yAxis: {},
        series: [
          {
            name: "价格",
            type: "line",
            data: this.historyProduct.historyPrice,
            itemStyle : { normal: {label : {show: true}}}
          }
        ],
        tooltip: {
          trigger: "axis",
          textStyle: { // 文字提示样式
            color: '#fff',
            fontSize: '12'
          },
          axisPointer: {
            type: "cross"
          },
        },
      })
      window.addEventListener("resize", () => {
        this.chart.resize()
      })
    },
    OpenChart() {
      this.$nextTick(() => {
        this.DrawHistoryChart()
      })
    },
    CloseChart() {
      window.removeEventListener("resize", () => {
        this.chart.resize()
      })
    },
    ConfirmNewTrace() {
      axios.post("/product/trace/add/",
          { // 请求体
            product_name: this.addTraceInfo.product_name,
            platform: this.addTraceInfo.platform,
            user_id: sessionStorage.getItem('user_id'),
            product_id: this.addTraceInfo.product_id,
            target_price: this.addTraceInfo.target_price
          })
          .then(response => {
            ElMessage.success("商品追踪成功") // 显示消息提醒
          })
          .catch(error => {
            ElMessage.error("商品追踪失败")
          })
          .finally(() => {
            this.addTraceVisible = false // 将对话框设置为不可见
          })
        },
  },
  mounted() {
    if (JSON.parse(localStorage.getItem('historySearch'))) {
      this.historySearch = JSON.parse(localStorage.getItem('historySearch'))
    }
    for (let i=0; i<3; i++) {
      this.CheckLogin(i)
    }
  },
}

</script>

<style>

.cardBox {
    height: 300px;
    width: 200px;
    box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
    text-align: center;
    margin-top: 40px;
    margin-left: 28px;
    margin-right: 10px;
    padding: 0 10px 10px;
}

.titleShow {
  text-overflow: ellipsis;
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
}

.merchantShow {
  margin-top: 5px;
  line-height: 12px;
  text-overflow: ellipsis;
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
}

.loading {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;
  .load-box {
    background-color: rgba(0, 0, 0, .5);
    width: 100px;height: 100px;border-radius: 5px;
    box-shadow:0px 1px 15px rgba(0,0,0, .5);color: #fff;
    display: flex;flex-direction: column;align-items: center;
    justify-content: center;letter-spacing: .8px;
    font-size: 13px;
    img{
      width: 30px;margin-bottom: 8px;
      -webkit-animation:rotate .8s linear infinite;
    }
  }
}
</style>